// BluetoothDataSender.java
package v2;

import org.freedesktop.dbus.connections.impl.DBusConnection;
import org.freedesktop.dbus.exceptions.DBusException;
import org.freedesktop.dbus.messages.MethodCall;

/**
 * 蓝牙数据发送器 - 向移动端发送数据 (dbus-java 3.3.2)
 */
public class BluetoothDataSender {
    private DBusConnection connection;

    public BluetoothDataSender() throws DBusException {
        this.connection = DBusConnection.getConnection(DBusConnection.DEFAULT_SYSTEM_BUS_ADDRESS);
    }

    /**
     * 发送数据到指定蓝牙设备
     */
    public void sendDataToDevice(String deviceMac, String data) throws DBusException {
        String devicePath = "/org/bluez/hci0/dev_" + deviceMac.replace(":", "_");

        System.out.println("📤 发送数据到设备: " + deviceMac);
        System.out.println("数据内容: " + data);

        try {
            // 通过方法调用发送数据
            sendViaMethodCall(devicePath, data);

            System.out.println("✅ 数据发送完成");

        } catch (Exception e) {
            System.err.println("❌ 发送数据失败: " + e.getMessage());
            throw new DBusException("发送失败: " + e.getMessage());
        }
    }

    /**
     * 通过方法调用发送数据
     */
    private void sendViaMethodCall(String devicePath, String data) throws DBusException {
        try {
            // 创建方法调用
            MethodCall call = new MethodCall(
                    "org.bluez",          // dest - 目标服务名
                    devicePath,           // path - 对象路径
                    "org.bluez.Device1",  // iface - 接口名
                    "Connect",            // member - 方法名
                    (byte) 0,             // flags - 标志位
                    ""                   // sig - 参数签名（空字符串表示无参数）
            );

            // 发送方法调用
            connection.sendMessage(call);

            System.out.println("✅ 方法调用发送成功");

        } catch (DBusException e) {
            System.err.println("方法调用发送失败: " + e.getMessage());
            // 尝试其他方式
            sendViaRawSignal(devicePath, data);
        }
    }

    /**
     * 通过原始信号发送数据
     */
    private void sendViaRawSignal(String devicePath, String data) throws DBusException {
        try {
            // 创建自定义信号
            DbusSignals.CustomBluetoothSignal signal = new DbusSignals.CustomBluetoothSignal(devicePath, data);

            // 发送信号
            connection.sendMessage(signal);

            System.out.println("✅ 信号方式发送成功");

        } catch (DBusException e) {
            System.err.println("信号发送失败: " + e.getMessage());
            throw e;
        }
    }

    /**
     * 发送 WiFi 配置到设备
     */
    public void sendWifiConfig(String deviceMac, String ssid, String password) throws DBusException {
        String config = String.format("WIFI:%s:%s", ssid, password);
        sendDataToDevice(deviceMac, config);
    }

    /**
     * 发送控制指令到设备
     */
    public void sendControlCommand(String deviceMac, String command, String... parameters)
            throws DBusException {
        StringBuilder sb = new StringBuilder("CMD:").append(command);
        for (String param : parameters) {
            sb.append(":").append(param);
        }
        sendDataToDevice(deviceMac, sb.toString());
    }

    /**
     * 连接蓝牙设备
     */
    public void connectDevice(String deviceMac) throws DBusException {
        String devicePath = "/org/bluez/hci0/dev_" + deviceMac.replace(":", "_");

        try {
            MethodCall call = new MethodCall(
                    "org.bluez",          // dest - 目标服务名
                    devicePath,           // path - 对象路径
                    "org.bluez.Device1",  // iface - 接口名
                    "Connect",            // member - 方法名
                    (byte) 0,             // flags - 标志位
                    ""                   // sig - 参数签名（空字符串表示无参数）
            );

            connection.sendMessage(call);
            System.out.println("✅ 连接设备: " + deviceMac);

        } catch (DBusException e) {
            System.err.println("连接设备失败: " + e.getMessage());
            throw e;
        }
    }

    /**
     * 断开设备连接
     */
    public void disconnectDevice(String deviceMac) throws DBusException {
        String devicePath = "/org/bluez/hci0/dev_" + deviceMac.replace(":", "_");

        try {
            MethodCall call = new MethodCall(
                    "org.bluez",          // dest - 目标服务名
                    devicePath,           // path - 对象路径
                    "org.bluez.Device1",  // iface - 接口名
                    "Disconnect",            // member - 方法名
                    (byte) 0,             // flags - 标志位
                    ""                   // sig - 参数签名（空字符串表示无参数）
            );

            connection.sendMessage(call);
            System.out.println("✅ 断开设备连接: " + deviceMac);

        } catch (DBusException e) {
            System.err.println("断开连接失败: " + e.getMessage());
            throw e;
        }
    }

    public void close() {
        if (connection != null) {
            connection.disconnect();
        }
    }
}